package aggregation

import (
	"io"
	"net/url"
	"time"

	"gitee.com/bjf-fhe/apicat/entry"
	"gitee.com/bjf-fhe/apicat/entry/etype"
)

func ToRemoteEntry(en *entry.LogEntry, mid ...string) *Entry {
	var report = &Entry{
		Url:        en.Url,
		Method:     en.Method,
		Protocol:   en.Protocol,
		Client:     en.Client,
		StatusCode: int32(en.StatusCode),
		Query:      en.Query.Encode(),
		Created:    en.Created.Unix(),
		ErrorType:  int64(en.ErrorType),
		Count:      en.Count,
	}
	if len(mid) > 0 {
		report.Machine = &MachineInfo{
			Id: mid[0],
		}
	}
	return report
}

func ToRemoteErrorMsg(err error, mid string) *Entry {

	var entry = &Entry{
		OtherError: &Error{
			Message: err.Error(),
		},
		Machine: &MachineInfo{
			Id: mid,
		},
	}

	if err == io.EOF {
		entry.OtherError.Type = ErrorType_ErrorTypeEOF
	} else {
		entry.OtherError.Type = ErrorType_ErrorTypeOther
	}
	return entry
}

func (e *Entry) ToLogEntryResponse() *entry.LogEntryResponse {
	var query url.Values
	if e.Query != "" {
		query, _ = url.ParseQuery(e.Query)
	}

	var res = new(entry.LogEntryResponse)

	if e.OtherError != nil {
		res.Error = &entry.LogError{
			MachineId: e.Machine.Id,
		}
		if e.OtherError.Type == ErrorType_ErrorTypeEOF {
			res.Error.Error = io.EOF
		} else {
			res.Error.Error = e.OtherError
		}
	} else {

		res.Entry = &entry.LogEntry{
			// Url        string     `json:"u"`
			Url: e.Url,
			// Method     string     `json:"m,omitempty"`
			Method: e.Method,
			// Protocol   string    `json:"p,omitempty"`
			Protocol: e.Protocol,
			// Client     string     `json:"c,omitempty"` //client ip
			Client: e.Client,
			// StatusCode int        `json:"s,omitempty"`
			StatusCode: int(e.StatusCode),
			// Query      url.Values `json:"q,omitempty"`
			Query: query,
			// Created   time.Time        `json:"t"`
			Created:   time.Unix(e.Created, 0),
			ErrorType: etype.EntryError(e.ErrorType),
			Count:     e.Count,
			MachineId: e.Machine.Id,
		}

	}
	return res
}
